package com.lottery.system.rabbitmq;

import com.rabbitmq.client.*;

import java.io.IOException;
import java.util.concurrent.TimeoutException;

/**
 * @author: xiaoxie
 * create: 2024-09-23 22:07
 * @BelongsProject: study-rabbitmq
 * @BelongsPackage: com.lottery.system.rabbitmq
 * description: rabbit mq的消费者
 */
public class Consumer {
    public static void main(String[] args) throws IOException, TimeoutException, InterruptedException {
        //1.建立连接
        ConnectionFactory factory = new ConnectionFactory();
        //ip
        factory.setHost("81.70.210.221");
        //端口号
        factory.setPort(5672);
        //用户名
        factory.setUsername("study");
        //密码
        factory.setPassword("010920");
        //虚拟机
        factory.setVirtualHost("study");
        //
        Connection connection = factory.newConnection();
        //2.创建信道
        Channel channel = connection.createChannel();
        //3.声明交换机,由于是入门所以就使用默认的交换机
        //4.声明队列
        /*
         * @param: queue: 队列名称 durable: 是否持久化 exclusive: 是否独占(一个消费者使用)
         *         autoDelete: 是否自动删除 arguments: 参数
         */
        channel.queueDeclare("test",true,false,false,null);
         DefaultConsumer consumer = new DefaultConsumer(channel) {
            @Override
            public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
                System.out.println("Received: " + new String(body));
            }
        };
         //5.消费消息
        /*
         * @param: queue: 队列名称  autoAck: 是否自动确认 callback: 接收到消息后的执行逻辑
         **/
         channel.basicConsume("test",true,consumer);
         Thread.sleep(2000);
         channel.close();
         connection.close();

    }
}
